<template>
  <div class="dashboard-editor-container">

    <!--    <panel-group @handleSetLineChartData="handleSetLineChartData" />-->

    <el-row style="background:#fff;padding:16px 16px 0;margin-bottom:32px;">
      <el-col :xs="24" :sm="24" :lg="6">
        <div class="chart-wrapper">
          <pie-chart :chart-data="pieChartData"/>
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="12">
        <div class="map-wrapper">
          <Map />
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="6">
        <div class="chart-wrapper">
          <bar-chart :chart-data="barChartData"/>
        </div>
      </el-col>
    </el-row>

    <el-row style="background:#fff;padding:16px 16px 0;margin-bottom:32px;">
      <line-chart :chart-data="lineChartData" />
    </el-row>



  </div>

</template>

<script>
import PanelGroup from '../../dashboard/PanelGroup'
import LineChart from '../../dashboard/LineChart'
import RaddarChart from '../../dashboard/RaddarChart'
import PieChart from '../../dashboard/PieChart'
import BarChart from '../../dashboard/BarChart'
import {getWeeklyApplyData, listApply} from "@/api/system/apply";
import Map from "@/views/dashboard/Map.vue";
import {listAvailable} from "@/api/system/available";

const lineChartData = {
  newVisitis: {
    expectedData: [100, 120, 161, 134, 105, 160, 165],
    actualData: [120, 82, 91, 154, 162, 140, 145]
  },
  messages: {
    expectedData: [200, 192, 120, 144, 160, 130, 140],
    actualData: [180, 160, 151, 106, 145, 150, 130]
  },
  purchases: {
    expectedData: [80, 100, 121, 104, 105, 90, 100],
    actualData: [120, 90, 100, 138, 142, 130, 130]
  },
  shoppings: {
    expectedData: [130, 140, 141, 142, 145, 150, 160],
    actualData: [120, 82, 91, 154, 162, 140, 130]
  }
}

export default {
  name: 'Index',
  components: {
    Map,
    // PanelGroup,
    LineChart,
    RaddarChart,
    PieChart,
    BarChart
  },
  data() {
    return {
      lineChartData: {
        expectedData: [],
        actualData: []
      },
      pieChartData: [],
      barChartData: {},
      jobData: [],
      applyData: []
      // lineChartData: lineChartData.newVisitis
    }
  },
  created() {
    this.fetchWeeklyApplyData();
    this.fetchJobAndApplyData();
  },
  methods: {
    fetchJobAndApplyData() {
      // 获取岗位数据
      listAvailable({}).then(response => {
        this.jobData = response.rows;
        this.processPieChartData();
        this.processBarChartData();
      });

      // 获取报名数据
      listApply({}).then(response => {
        this.applyData = response.rows;
        this.processPieChartData();
        this.processBarChartData();
      });
    },

    processPieChartData() {
      // 初始化统计数据
      const stats = {
        technicalJobs: 0,      // 技术工岗位数
        generalJobs: 0,        // 普通工岗位数
        managementJobs: 0,     // 管理岗岗位数
        technicalApplies: 0,   // 技术工报名数
        generalApplies: 0,     // 普通工报名数
        managementApplies: 0   // 管理岗报名数
      };

      // 统计岗位数据
      this.jobData.forEach(job => {
        const nature = job.positionNature || '';
        const count = job.positionNumber || 0;

        if (nature.includes('技术')) {
          stats.technicalJobs += count;
        } else if (nature.includes('普通')) {
          stats.generalJobs += count;
        } else if (nature.includes('管理')) {
          stats.managementJobs += count;
        }
      });

      // 统计报名数据
      this.applyData.forEach(apply => {
        const nature = apply.positionNature || '';

        if (nature.includes('技术')) {
          stats.technicalApplies += 1;
        } else if (nature.includes('普通')) {
          stats.generalApplies += 1;
        } else if (nature.includes('管理')) {
          stats.managementApplies += 1;
        }
      });

      // 构造饼图数据
      this.pieChartData = [
        { value: stats.technicalJobs, name: '技术工岗位' },
        { value: stats.generalJobs, name: '普通工岗位' },
        { value: stats.managementJobs, name: '管理岗岗位' },
        { value: stats.technicalApplies, name: '技术工报名' },
        { value: stats.generalApplies, name: '普通工报名' },
        { value: stats.managementApplies, name: '管理岗报名' }
      ];
    },

    processBarChartData() {
      // 确保有数据再处理
      if (!this.applyData || this.applyData.length === 0) {
        return;
      }

      // 定义单位映射关系
      const deptMapping = {
        100: '直属单位',
        101: '一号单位',
        102: '二号单位',
        103: '三号单位'
      };

      // 初始化统计数据
      const deptStats = {
        '直属单位': { technical: 0, general: 0, management: 0 },
        '一号单位': { technical: 0, general: 0, management: 0 },
        '二号单位': { technical: 0, general: 0, management: 0 },
        '三号单位': { technical: 0, general: 0, management: 0 }
      };

      // 统计各机构各岗位性质的报名数量
      this.applyData.forEach(apply => {
        const deptId = apply.deptId;
        const nature = apply.positionNature || '';

        // 只处理指定的部门ID
        if ([100, 101, 102, 103].includes(deptId)) {
          const deptName = deptMapping[deptId];

          if (nature.includes('技术')) {
            deptStats[deptName].technical += 1;
          } else if (nature.includes('普通')) {
            deptStats[deptName].general += 1;
          } else if (nature.includes('管理')) {
            deptStats[deptName].management += 1;
          }
        }
      });

      // 构造柱状图数据
      this.barChartData = {
        xAxisData: ['直属单位', '一号单位', '二号单位', '三号单位'],
        series: [
          {
            name: '技术工',
            type: 'bar',
            stack: '总量',
            data: [
              deptStats['直属单位'].technical,
              deptStats['一号单位'].technical,
              deptStats['二号单位'].technical,
              deptStats['三号单位'].technical
            ]
          },
          {
            name: '普通工',
            type: 'bar',
            stack: '总量',
            data: [
              deptStats['直属单位'].general,
              deptStats['一号单位'].general,
              deptStats['二号单位'].general,
              deptStats['三号单位'].general
            ]
          },
          {
            name: '管理岗',
            type: 'bar',
            stack: '总量',
            data: [
              deptStats['直属单位'].management,
              deptStats['一号单位'].management,
              deptStats['二号单位'].management,
              deptStats['三号单位'].management
            ]
          }
        ]
      };
    },

    fetchWeeklyApplyData() {
      getWeeklyApplyData().then(response => {
        const data = response.rows;

        // 按天聚合报名人数
        const dailyCount = {};
        // 按天聚合审批通过人数
        const dailypassCount = {};
        data.forEach(item => {
          const date = item.createTime.split(' ')[0]; // 取日期部分
          dailyCount[date] = (dailyCount[date] || 0) + 1;
          const passYN = item.statusApply
          if(passYN === '1'){
            dailypassCount[date] = (dailypassCount[date] || 0) + 1;
          }

        });

        // 生成最近7天的日期数组（格式：YYYY-MM-DD）
        const today = new Date();
        const dates = [];
        for (let i = 6; i >= 0; i--) {
          const date = new Date();
          date.setDate(today.getDate() - i);
          dates.push(date.toISOString().split('T')[0]);
        }

        // 生成按天排序的报名人数数组
        const expectedData = dates.map(date => dailyCount[date] || 0);
        const actualData = dates.map(date => dailypassCount[date] || 0);; // 可以根据实际需要扩展

        this.lineChartData = {
          expectedData: expectedData,
          actualData: actualData
        };
      });
    },
    handleSetLineChartData(type) {
      this.lineChartData = lineChartData[type]
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 32px;
  background-color: rgb(240, 242, 245);
  position: relative;

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }

}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }

  .map-wrapper {
    background: #fff;
    padding:  0px 0px 0;
    margin-bottom: 32px;
    height: 400px;
  }

}
</style>
